package com.uzai.console.service.hdk.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jd.open.api.sdk.JdClient;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.entity.PyqHdkGoods;
import com.uzai.console.mapper.PyqHdkGoodsMapper;
import com.uzai.console.mapper.SysConfigMapper;
import com.uzai.console.service.hdk.HdkGoodsService;
import com.uzai.console.service.kuizhan.KuaiZhanService;
import com.uzai.console.vo.hdk.HdkGoods;
import com.uzai.console.vo.hdk.HdkSelectedItemResulit;
import com.uzai.console.vo.kuaizhan.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 好单库商品实现类
 * @author liuqi
 * @date 2022年01月16日 17:14
 */
@Service
public class HdkGoodsServiceImpl implements HdkGoodsService {

    Logger logger = LoggerFactory.getLogger(HdkGoodsServiceImpl.class);

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private PyqHdkGoodsMapper pyqHdkGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Async("taskExecutor")
    @Override
    public void downLoadHdkGoodsSync() {
        //限流key
        String taskLimitKet = "-downLoadHdkGoodsSync-taskLimitKey-";
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if(object != null){
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        logger.info("-----调用好单库自动下载商品线程--xxlJob start--");
        downLoadHdkGoods(1);

        //删除限流key
        redisTemplate.delete(taskLimitKet);
    }

    @Async("taskExecutor")
    @Override
    public void deleteHdkGoodsSync() {
        int deleteDay = DateUtil.getNowTime() - 30*24*3600;
        deleteBeforeDay(deleteDay);
    }

    private void downLoadHdkGoods(int min_id) {
        try {
            String hdkPyqapi = uzaiConsoleSysConfig.getHdkPyqapi();
            String hdkApikey = uzaiConsoleSysConfig.getHdkApikey();
            hdkPyqapi = hdkPyqapi + "?apikey=" + hdkApikey + "&min_id=" + min_id;
            ResponseEntity<String> response = restTemplate.getForEntity(hdkPyqapi, String.class);
            if (response!=null && response.getStatusCode() == HttpStatus.OK){
                //远程调用失败，获取msg异常信息，根据自己的业务进行合理处理
                HdkSelectedItemResulit hdkSelectedItemResulit = JSONObject.parseObject(response.getBody(), HdkSelectedItemResulit.class);
                if(hdkSelectedItemResulit != null && "1".equals(hdkSelectedItemResulit.getCode())){
                    List<HdkGoods> hdkGoodsList = JSONObject.parseArray(JSONObject.toJSONString(hdkSelectedItemResulit.getData()), HdkGoods.class);
                    if (hdkGoodsList != null && hdkGoodsList.size() > 0){
                        hdkGoodsAdd(hdkGoodsList);
                        downLoadHdkGoods(hdkSelectedItemResulit.getMin_id());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("-----downLoadHdkGoods sync err={}", e.getMessage());
        }
    }

    private void hdkGoodsAdd(List<HdkGoods> hdkGoodsList) {
        int now = DateUtil.getNowTime();
        if (hdkGoodsList==null || hdkGoodsList.size() ==0 ){
            return ;
        }

        logger.info("---好单库商品下载--size={}",hdkGoodsList.size());

        for (HdkGoods hdkGoods : hdkGoodsList){
            //查询今天该订单是否存在，如果存在，则不处理
            Integer showTime =  hdkGoods.getShow_time();
            if(showTime == null){
                continue;
            }
            String addDay = DateFormatUtil.format(new Date(showTime*1000L), "yyyy-MM-dd");
            PyqHdkGoods pyqHdkGoods = pyqHdkGoodsMapper.selectByItemidAndAddDay(hdkGoods.getItemid(), addDay);
            if (pyqHdkGoods == null){
                pyqHdkGoods = new PyqHdkGoods();
                pyqHdkGoods.setId(IdWorker.getId());
                pyqHdkGoods.setItemid(hdkGoods.getItemid());
                pyqHdkGoods.setItempic(Tools.getStr(hdkGoods.getItempic()));
                pyqHdkGoods.setItemtitle(Tools.getStr(hdkGoods.getItemtitle()));
                pyqHdkGoods.setCouponurl(Tools.getStr(hdkGoods.getCouponurl()));
                String couponid = Tools.getParameterMap(pyqHdkGoods.getCouponurl()).get("activityId");
                pyqHdkGoods.setCouponid(couponid);
                pyqHdkGoods.setContent(String2Json(Tools.getStr(hdkGoods.getContent())));
                pyqHdkGoods.setComment(String2Json(Tools.getStr(hdkGoods.getComment())));
                pyqHdkGoods.setAddTime(Tools.getInteger(hdkGoods.getAdd_time()));
                pyqHdkGoods.setShowTime(Tools.getInteger(hdkGoods.getShow_time()));
                pyqHdkGoods.setItemendprice(Tools.getDouble(hdkGoods.getItemendprice()));
                pyqHdkGoods.setCouponmoney(Tools.getDouble(hdkGoods.getCouponmoney()));
                pyqHdkGoods.setSolaImage(Tools.getStr(hdkGoods.getSola_image()));
                pyqHdkGoods.setDummyClickStatistics(Tools.getStr(hdkGoods.getDummy_click_statistics()));
                pyqHdkGoods.setItemprice(Tools.getDouble(hdkGoods.getItemprice()));
                pyqHdkGoods.setTkrates(Tools.getDouble(hdkGoods.getTkrates()));
                pyqHdkGoods.setShowContent(String2Json(Tools.getStr(hdkGoods.getShowContent())).replace("$淘口令$","[淘口令]"));
                pyqHdkGoods.setCopyContent(String2Json(Tools.getStr(hdkGoods.getCopyContent())).replace("$淘口令$","[淘口令]"));
                pyqHdkGoods.setCopyComment(String2Json(Tools.getStr(hdkGoods.getCopyComment()).replace("$淘口令$","[淘口令]")));
                pyqHdkGoods.setShowComment(String2Json(Tools.getStr(hdkGoods.getShowComment())).replace("$淘口令$","[淘口令]"));
                pyqHdkGoods.setAddDay(addDay);
                pyqHdkGoods.setType(1); //好单库
                pyqHdkGoods.setPlatform(0); //淘宝
                pyqHdkGoods.setCreateTime(now);
                pyqHdkGoods.setUpdateTime(now);
                pyqHdkGoodsMapper.insert(pyqHdkGoods);
            }
        }
    }

    private String String2Json(String str){
        str = str.replaceAll("&lt;","<").replaceAll("&gt;",">").replaceAll("<br>","\n");
        return str;
    }


    /**
     * 删除多少天之前的商品
     * @author liuqi
     * @date 2022/6/24 16:55
     * @param beforeDay
     */
    private void deleteBeforeDay(int beforeDay) {
        pyqHdkGoodsMapper.deleteBeforeDay(beforeDay);
    }
}
